package com.yyy.example;

import com.yyy.common.annotation.MsgListener;
import com.yyy.example.entity.User01;
import com.yyy.entity.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yyy
 * @Date 2020-09-13 16:25
 * @Email yangyouyuhd@163.com
 */
@Slf4j
@RestController
public class ConsumerService {

    AtomicInteger[] arr = new AtomicInteger[3];

    @Async
    @MsgListener("queue00")
    public void consumer00(Message<User01> message) {
//        System.out.println("监听了队列queue00获取到的消息：" + message.getBody());
        message.basicAck();
        Object obj = arr[0] == null ? arr[0] = new AtomicInteger(1) : arr[0].incrementAndGet();
    }

    @Async
    @MsgListener("queue01")
    public void consumer01(Message<User01> message) {
        Object obj = arr[1] == null ? arr[1] = new AtomicInteger(1) : arr[1].incrementAndGet();
//        System.out.println("监听了队列queue01获取到的消息：" + message.getBody());
    }

    @Async
    @MsgListener("queue02")
    public void consumer02(Message<User01> message) {
        Object obj = arr[2] == null ? arr[2] = new AtomicInteger(1) : arr[2].incrementAndGet();
        //        System.out.println("监听了队列queue02获取到的消息：" + message.getBody());
    }

    @RequestMapping("/more/ConsumerVal")
    public String ewaResult() {
        return "consumer00消费了：" + arr[0].get() + "条消息" + "\n"
                + "consumer01消费了：" + arr[1].get() + "条消息" + "\n"
                + "consumer02消费了：" + arr[2].get() + "条消息";
    }


    AtomicInteger one = new AtomicInteger(0);

    @RequestMapping("/one/ConsumerVal")
    public String moveResult() {
        return "one 集群共消费了" + one.get();
    }

    @Async
    @MsgListener("queue04")
    public void consumer0401(Message<User01> message) {
        one.incrementAndGet();
//        System.out.println("0401 监听了队列queue04 获取的消息：" + message.getBody());
    }

    @Async
    @MsgListener("queue04")
    public void consumer0402(Message<User01> message) {
        one.incrementAndGet();
//        System.out.println("0402 监听了队列queue04 获取到的消息：" + message.getBody());
    }

    @Async
    @MsgListener("queue04")
    public void consumer0403(Message<User01> message) {
        one.incrementAndGet();
//        System.out.println("0403 监听了队列queue04 获取到的消息：" + message.getBody());
    }


    @MsgListener(QueueNameList.q1)
    public void consumerQ1(Message<User01> message) {
        log.error("成功消费了{}的一条消息：{}", QueueNameList.q1, message);
    }

    @MsgListener(QueueNameList.q2)
    public void consumerQ2(Message<User01> message) {
        log.error("异常消费了{}的一条消息：{}", QueueNameList.q2, message);
        throw new RuntimeException("这是异常信息");
    }
}
